package com.pybox.spec;

import com.pybox.entity.TUsers;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import java.util.*;


/**
 * 描述：TUsers Specification
 *
 * @author wuyingkai
 * @date 2018-09-15
 */


public class TUsersSpec implements Specification<TUsers> {

    private Map<String, String> params;

    public TUsersSpec(Map<String, String> params) {
        this.params = params;
    }

    @Override
    public Predicate toPredicate(Root<TUsers> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {


        String customerId = this.params.get("customerId");
        String groupId = this.params.get("groupId");
        String username = this.params.get("username");
        String realname = this.params.get("realname");
        String comments = this.params.get("comments");
        String deptId = this.params.get("deptId");
        String isAdmin = this.params.get("isAdmin");
        List<Predicate> ps = new ArrayList<>();

        ps.add(criteriaBuilder.equal(root.get("deleted"), 0));

        if (!StringUtils.isEmpty(customerId)) {
            ps.add(criteriaBuilder.equal(root.get("customerId"), customerId));
        }
        if (!StringUtils.isEmpty(groupId)) {
            ps.add(criteriaBuilder.equal(root.get("groupId"), groupId));
        }
        //前端传值可能引起误会修改查询
        if (!StringUtils.isEmpty(username)) {
            ps.add(criteriaBuilder.like(root.get("username"), "%" + username + "%"));
        }
        if (!StringUtils.isEmpty(realname)) {
            ps.add(criteriaBuilder.like(root.get("realname"), "%" + realname + "%"));
        }
        if (!StringUtils.isEmpty(comments)) {
            ps.add(criteriaBuilder.like(root.get("comments"), "%" + comments + "%"));
        }
        if (!StringUtils.isEmpty(deptId)) {
            ps.add(criteriaBuilder.equal(root.get("deptId"), deptId));
        }
//        if (!StringUtils.isEmpty(isAdmin)) {
//            ps.add(criteriaBuilder.equal(root.get("isAdmin"), isAdmin));
//        }

        criteriaQuery = criteriaQuery.where(ps.toArray(new Predicate[ps.size()]));

        return criteriaQuery.getRestriction();
    }

}